package com;
 import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

   
 public class Indexer {  
    // private static Log log = LogFactory.getLog(Indexer.class);  
   
     public static void main(String[] args) throws Exception {  
         File indexDir = new File("E:\\index");  
         File dataDir = new File("E:\\Ibm\\资料");  
   
         long start = new Date().getTime();  
   
         int numIndexed = index(indexDir, dataDir);  
   
         long end = new Date().getTime();  
   
         System.out.println("use:" + (end - start)); 
         System.out.println("Index " + numIndexed + " file(s)");
     }  
   
     public static int index(File indexDir, File dataDir) {  
         int ret = 0;  
         try {  
             IndexWriter writer = new IndexWriter(indexDir, new StandardAnalyzer(), true);  
             writer.setUseCompoundFile(false);  
   
             indexDirectory(writer, dataDir);  
   
             ret = writer.docCount();  
             writer.optimize();  
             writer.close();  
   
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
         return ret;  
     }  
   
     public static void indexDirectory(IndexWriter writer, File dir) {  
         try {  
             File[] files = dir.listFiles();  
   
             for (File f : files) {  
                 if (f.isDirectory()) {  
                     indexDirectory(writer, f);  
                 } else {  
                     indexFile(writer, f);  
                 }  
             }  
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
     }  
   
     public static void indexFile(IndexWriter writer, File f) {  
         try {  
             System.out.println("Indexing:" + f.getCanonicalPath());  
             Document doc = new Document();  
             Reader txtReader = new FileReader(f);
             
             doc.add(Field.Text("contents", txtReader));  
             doc.add(Field.Keyword("filename", f.getCanonicalPath()));
             doc.add(Field.Keyword("title",f.getAbsolutePath()));
             
             writer.addDocument(doc);  
   
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
     }  
 }  
